package com.zhglxt.oa.activitiListeners.eventListener;

import com.zhglxt.oa.entity.Notify;
import com.zhglxt.oa.service.INotifyService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Map;

/**
 * @ClassName OwnEventListener
 * @Description 自定义事件监听，任务执行操作是触发某些操作
 * @Author moyongjun
 * @Date 2022/6/5 08:22
 * @Version 1.0
 **/

public class OwnEventListener implements ActivitiEventListener, Serializable {
    private final Logger logger = LoggerFactory.getLogger(OwnEventListener.class);
    @Autowired
    private INotifyService notifyService;
    @Autowired
    RuntimeService runtimeService;
    @Override
    public void onEvent(ActivitiEvent activitiEvent) {

        ActivitiEventType type = activitiEvent.getType();
        logger.info("当前的获取的事件类型对象是：", type);
        logger.info("当前的事件类型是：", type.name());
        String processInstanceId = activitiEvent.getProcessInstanceId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();

        logger.info("当前的流程实例：{}", processInstanceId);
        // 任务完成时触发操作
        if (type == ActivitiEventType.ACTIVITY_COMPLETED) {
            // todo
            Notify notify = new Notify();
            notify.setNotifyContent("您有一个新的待办任务，请查收。");

            Map<String, Object> processVariables = processInstance.getProcessVariables();
            String auditUserId = (String)processVariables.get("auditUserId");
            logger.info("下一任务节点的审批人ID是：{}",auditUserId);
            notify.setUserId(auditUserId);

            // 设置发布状态
            notify.setStatus("1");
            notifyService.insertNotify(notify);
            logger.info("发送了一个通知，等待任务接收人查看");
        }
    }

    @Override
    public boolean isFailOnException() {
        logger.info("事件是否失败：");
        return false;
    }


}
